package com.hongtech.tiny.common.service;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class DingTalkAccessToken {

    private static final String TOKEN_URL = "https://oapi.dingtalk.com/gettoken";

    private String appKey;

    private String appSecret;

    private String accessToken = null;

    private long expirationTime = 0;


    public DingTalkAccessToken(String appKey, String appSecret) {
        this.appKey = appKey;
        this.appSecret = appSecret;
    }

    // 获取 DingTalk 的 access_token
    public String getAccessToken() throws IOException {
        long currentTime = System.currentTimeMillis() / 1000;  // 当前时间，以秒为单位

        // 如果缓存的 access_token 没有过期，直接返回
        if (accessToken != null && currentTime < expirationTime) {
            System.out.println("Using cached access token.");
            return accessToken;
        }

        // 如果缓存的 access_token 已过期，重新获取
        System.out.println("Access token expired or not available. Fetching a new one...");
        String tokenResponse = fetchNewAccessToken();
        parseAndCacheAccessToken(tokenResponse);

        return accessToken;
    }

    // 向 DingTalk 获取新的 access_token
    private String fetchNewAccessToken() throws IOException {
        // 构建请求 URL
        String urlStr = TOKEN_URL + "?appkey=" + appKey + "&appsecret=" + appSecret;
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        // 读取响应
        try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
            return response.toString();
        }
    }

    // 解析返回的 JSON 响应并缓存 access_token 和过期时间
    private void parseAndCacheAccessToken(String response) {
        try {
            // 解析 JSON 响应
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.getInt("errcode") == 0) {
                accessToken = jsonObject.getString("access_token");
                long expiresIn = jsonObject.getLong("expires_in");  // access_token 的有效期（秒）
                expirationTime = System.currentTimeMillis() / 1000 + expiresIn;  // 设置过期时间
                System.out.println("New access token cached. Expiration time: " + expirationTime);
            } else {
                System.out.println("Failed to get access token: " + jsonObject.getString("errmsg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

